﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AVIS.OutBound.Countrys.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.Countrys
{
    public class CountryManager : DomainService, ICountryManager
    {
        private readonly IRepository<Country> _CountryRepository;
        private readonly IObjectMapper _objectMapper;
        private readonly ICacheManager _CacheManager;

        public CountryManager(IRepository<Country> CountryRepository,
            IObjectMapper objectMapper,
            ICacheManager CacheManager)
        {
            _CountryRepository = CountryRepository;
            _objectMapper = objectMapper;
            _CacheManager = CacheManager;

        }

        /// <summary>
        /// 获取指定编号的国家信息
        /// </summary>
        /// <param name="Code">编号</param>
        /// <param name="enName">英文名称</param>
        /// <returns></returns>
        public Country GetCountry(string code, string enName)
        {
            var cacheKey = code.ToUpper() + "_" + enName.ToUpper();
            var country = _CacheManager.GetCountryCache().Get(cacheKey, c => GetCountryCacheItem(code, enName));
            var countrydata = _objectMapper.Map<Country>(country);
            return countrydata;
        }

        /// <summary>
        /// 获取指定Code的国家信息
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        private CountryCacheItem GetCountryCacheItem(string Code, string enName)
        {
            var country = _CountryRepository.FirstOrDefault(c => c.Code == Code && c.ENName == enName);
            var cacheItem = _objectMapper.Map<CountryCacheItem>(country);
            return cacheItem;
        }


    }
}
